package cqrtplm.listener;

import cn.hutool.extra.spring.SpringUtil;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.model.constant.ProcessConstant;
import com.hustcad.plm.pdm.workflow.model.entity.FlowTaskInfo;
import com.hustcad.plm.pdm.workflow.service.TyplmFlowableTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CustomListener(category = "润通", description = "会签节点自动完成")
@Slf4j
public class RTAutoCompleteListener implements ExecutionListener {
    @Override
    public void notify(DelegateExecution delegateExecution) {
        String workFlowContainerId = delegateExecution.getProcessInstanceBusinessKey();
        if (StringUtils.isBlank(workFlowContainerId)) {
            workFlowContainerId = delegateExecution.getVariable(ProcessConstant.WORK_FLOW_CONTAINER_ID).toString();
        }

        TyplmFlowableTaskService typlmFlowableTaskService = SpringUtil.getBean(TyplmFlowableTaskService.class);
        TaskService taskService = SpringUtil.getBean(TaskService.class);
        Map<String, Object> params = new HashMap<>();
        params.put("workFlowContainerId", new BigInteger(workFlowContainerId));
        List<FlowTaskInfo> flowTaskInfos = typlmFlowableTaskService.queryTaskByParams(params);
        for (FlowTaskInfo flowTaskInfo : flowTaskInfos) {
            taskService.complete(flowTaskInfo.getTaskId());
        }
        log.info("进入自动完成监听");
    }

}
